<!DOCTYPE html>
<html>
  <head>
    <script src='/_ah/channel/jsapi'></script>
    <script type='text/javascript' src='js/jquery.js'></script>
    <script type='text/javascript' src="js/Three.js"></script>
    <script type='text/javascript' src="js/ThreeSpriteRenderer.js"></script>
    <script type='text/javascript' src="js/coopy_renderer.js"></script>
    <script type='text/javascript' src="js/coopy_com.js"></script>
    <link rel="stylesheet" type="text/css" href="stylesheets/main.css" />
    <style type="text/css">

form{margin:0;padding:0;}
fieldset{margin:1em 0;border:none;font-size:10px;border-top:1px solid #ccc;}
legend{margin:1em 0;padding:0 .5em;color:#036;background:transparent;font-size:1.3em;font-weight:bold;}
label{float:left;width:100px;padding:0 1em;text-align:right;}
fieldset div{margin-bottom:.5em;padding:0;display:block;}
fieldset div input,fieldset div textarea{width:150px;border-top:1px solid #555;border-left:1px solid #555;border-bottom:1px solid #ccc;border-right:1px solid #ccc;padding:1px;color:#333;}
fieldset div select{padding:1px;}


    </style>
  </head>
  <body>
   <script type='text/javascript'>

    // variables possibly relevant to set
    var renderMode = {{ rendermode }}; // 0 = 2D sprites, 1 = 3D Canvas, low poly models, 2 = 3DWebGL, high poly models; 3 = WebGL + override check
    var current_width = 1024;
    
    var JSON = JSON || {};
    var state = {
        game_key: '{{ game_key }}',
        me: '{{ me }}'
    };
    var deltaState = {};



    // 2D relevant vars
    var spritescale = 40.0;

    var angle = 0;
    var vector_x = 1.0;
    var vector_y = 0.0;
    var force = 1.0;

    var drawscale = {
      x : current_width/32.0,
      y : current_width/32.0
      }
    var viewportdiv = null;

    var alert_div_id = 0;
    var alert_div_vpos = 600;

    // modifator variables
    var mdf_timer, mdf_modifier, mfd_increase;
    var force_modifier = [1,1,1,1,1,5,5,5,5,25,25,25,100,100,100,100,500,500,500,1000];

    // chatterbox variables
    var bChatterboxVisible = false;

    // debugger element
    var debugdiv = document.createElement("div");

    // fix rounding routine
    Math.nativeRound = Math.round;
    Math.round = function(i, iDecimals) {
        if (!iDecimals)
           return Math.nativeRound(i);
        else
            return Math.nativeRound(i * Math.pow(10, Math.abs(iDecimals))) / Math.pow(10, Math.abs(iDecimals));
    };

    var setVector = function() {
        var sign = function(x) {
            return (x>0)?1:((x<0)?-1:0);
        }
        var rad_x = Math.round(Math.cos(angle*Math.PI/180),3);
        var rad_y = Math.round(Math.sin(angle*Math.PI/180),3);
        if (Math.abs(rad_x)>Math.abs(rad_y)) {
            vector_y = Math.round(rad_y / Math.abs(rad_x),2);
            vector_x = sign(rad_x);
        } else {
            if (rad_y!=0) {
                vector_x = Math.round(rad_x / Math.abs(rad_y),2);
                vector_y = sign(rad_y);
            } else {
                vector_x = 0;
                vector_y = 0;
            }
        }
    }

    var tt=0;

    var mdf_force  = function () {
        oForm = document.getElementById("paramf");
        force = parseInt(oForm.elements["force"].value);
        f_delta = force_modifier[Math.min(mdf_modifier, force_modifier.length)-1];
        force += (mdf_increase)?f_delta:-f_delta;
        oForm.elements["force"].value = force;
        mdf_modifier += 1;
        mdf_timer = setTimeout("mdf_force()", 150);
        showCommand();
    }

    var mdf_angle  = function () {
        angle = (angle+mdf_modifier+360) % 360;
        setVector();
        mdf_timer = setTimeout("mdf_angle()", 200);
        angler(angle);
        showCommand();
    }

    var showAlert = function(alertmsg) {
        alert_div_id += 1;
        alert_div_vpos +=20;
        var alert_div = document.createElement('div');
        alert_div.id="alert"+alert_div_id;
        alert_div.setAttribute('style','position: absolute; left: '+parseInt(current_width/2-(alertmsg.length*16))+'px; top: '+ alert_div_vpos + 'px; height: 20px; color = #EEEEEE; background-color : #000000');
        alert_div.innerHTML = '<center>'+alertmsg+'</center>';
        document.body.appendChild(alert_div);
        $("#alert"+alert_div_id).animate( {top: '-=20', opacity : 0.25},
                                          {duration : 200, complete : function () {
                                                    alert_div_vpos -=20;
                                                    $(this).animate({top: '-=180', opacity : 0.25},
                                                                    {duration : 1000, complete : function() {$(this).remove()}})}} );
    }

    var showEnd = function () {
        var ending_div = document.createElement('div');
        ending_div.setAttribute('id','theend');
        ending_div.setAttribute('style','position: absolute; left: 200px; top: 200px; height: 80px; background-color : #f0b020');
        if (state.the_end.reason==1) { 
			ending_div.innerHTML = '<b>Mission complete.</b><br>'+state.the_end.msg+'<br><center><a href="/epilogue">Continue</a></center>';
		} else {
	        ending_div.innerHTML = '<b>Mission failed.</b><br>'+state.the_end.msg+'<br><center><a href="/epilogue">Continue</a></center>';
        }
        document.body.appendChild(ending_div);
    }
    
    var showMezzo = function (mezzo_html) {
        var mezzo_div = document.createElement('div');
        mezzo_div.setAttribute('id','mezzo');
        mezzo_div.setAttribute('class','mezzo');
        mezzo_div.setAttribute('style','width: '+parseInt(current_width)-200+'px');
        mezzo_div.innerHTML = mezzo_html;
        document.body.appendChild(mezzo_div);
    }

    var updateStatus = function() {
        $("#sQuadrant").html(state.pstatus.quadrant);
        $("#sSector").html(state.pstatus.sector);
        $("#sObjectives").html(state.pstatus.objectives);
        $("#sEnergy").html(state.pstatus.energy);
        var bg = state.pstatus.damage+"% 0px";
        $("#sDamage").css('backgroundPosition', bg);
        $("#sDamage").html(state.pstatus.damage);
        bg = (100-state.pstatus.shield)+"% 0px";
        $("#sShield").css('backgroundPosition', bg);
        $("#sShield").html(state.pstatus.shield);
    }

    var sendMessage = function(path, opt_param) {
      path += '?g=' + state.game_key;
      if (opt_param) {
        path += '&' + opt_param;
      }
      var xhr = new XMLHttpRequest();
      xhr.open('POST', path, true);
      xhr.send();
    };


    var onOpened = function() {
      sendMessage('/command',"cmnd=NONE&go=0");
    };

    function html_entity_decode(str) {
      var ta=document.createElement("textarea");
      ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
      return ta.value;
    };

    var onMessage = function(m) {
      d = html_entity_decode(m.data);
      deltaState = JSON.parse(d);
      if (deltaState.entities) {
          clearViewport();
      }
      state.ship = deltaState.ship || state.ship;
      state.pstatus = deltaState.pstatus || state.pstatus;
      state.alertmsg = deltaState.alertmsg || state.alertmsg;
      state.entities = deltaState.entities || state.entities;
      state.the_end = deltaState.the_end || state.the_end;
      state.mezzo = deltaState.mezzo || state.mezzo;
      state.animations = deltaState.animations || {}; // only capture the delta
      state.commands = deltaState.commands || {}; // only capture the delta
      if (deltaState.the_end) showEnd();
      if (deltaState.mezzo) {
          if (deltaState.mezzo.show) {
             showMezzo(deltaState.mezzo.html);
             state.mezzo.show = false;
          }
          if (deltaState.mezzo.discard) {
             document.body.removeChild(document.getElementById("mezzo"));
             state.mezzo.discard = false;
          }
      }
      if (deltaState.animations) {
          clearCommandExecutable();
          start_animations(deltaState.animations);
          timeCommandExecutable();
      };
      if (deltaState.pstatus) updateStatus();
      if (deltaState.alertmsg) showAlert(deltaState.alertmsg);
      if (deltaState.entities) {
          clearCommandExecutable();
          updateViewport(viewportdiv, debugdiv);
          timeCommandExecutable();
      }
      if (deltaState.commands) command.updateButtons (deltaState.commands);
    }

    var openChannel = function() {
      var token = '{{ token }}';
      var channel = new goog.appengine.Channel(token);
      var handler = {
        'onopen': onOpened,
        'onmessage': onMessage,
        'onerror': function() {},
        'onclose': function() {}
      }
      var socket = channel.open(handler);
      socket.onopen = onOpened;
      socket.onmessage = onMessage;
    }

    var scaleInterface = function(viewportdiv, viewportsizerdiv) {
        var h = (drawscale.y*20)+"px";
        var w = (drawscale.x*20)+"px";
        viewportdiv.style.height = h;
        viewportdiv.style.width = w;
        viewportsizerdiv.style.height = h;
        viewportsizerdiv.style.width = w;
        buttonwidth= Math.floor((current_width-320)/6);     // aantal buttons
        $("div.button").css("width",buttonwidth);
        var commanddiv = document.getElementById("command");
        commanddiv.style.width = (current_width-320);
        if (renderMode>0) {
            viewportdiv.orientation = {
                x : 10,
                y : 10,
                rotation : -1.0
            };
        } else {
            viewportdiv.orientation = {
                x : 0,
                y : 0,
                rotation : 1.0
            };
        }
    }

    var initialize = function() {
        openChannel();
        coopyData.load();
        command.initButtons();
        document.getElementById("mdf_fincr").onmousedown = new Function("{clearTimeout(mdf_timer); mdf_increase = true; mdf_modifier = 1; mdf_force()}");
        document.getElementById("mdf_fincr").onmouseup = new Function("{clearTimeout(mdf_timer)}");
        document.getElementById("mdf_fdecr").onmousedown = new Function("{clearTimeout(mdf_timer); mdf_increase = false; mdf_modifier = 1; mdf_force()}");
        document.getElementById("mdf_fdecr").onmouseup = new Function("{clearTimeout(mdf_timer)}");
        document.getElementById("mdf_cturn").onmousedown = new Function("{clearTimeout(mdf_timer); mdf_modifier = 45; mdf_angle()}");
        document.getElementById("mdf_cturn").onmouseup = new Function("{clearTimeout(mdf_timer)}");
        document.getElementById("mdf_ccturn").onmousedown = new Function("{clearTimeout(mdf_timer); mdf_modifier = -45; mdf_angle()}");
        document.getElementById("mdf_ccturn").onmouseup = new Function("{clearTimeout(mdf_timer)}");

        $('#chatfoldview').click(function () { $('#chatterbox').animate({right : ((bChatterboxVisible)?0:200), width : ((bChatterboxVisible)?16:216)},200); bChatterboxVisible = !bChatterboxVisible});

        if (current_width>($(window).width()-20)) {
            current_width=Math.floor(($(window).width()-20)/21)*32;
        }
        if ((current_width/2)>($(window).height()-220)) {
            current_width=Math.floor(($(window).height()-220)/21)*32;
        }
        drawscale.x = drawscale.y = parseInt(current_width/32.0);
        viewportdiv = document.getElementById("viewport");
        viewportsizerdiv = document.getElementById("viewportsizer");
        viewportdiv.appendChild(debugdiv);
        scaleInterface(viewportdiv, viewportsizer);
        renderInit(viewportdiv, renderMode);
    }
    setTimeout(initialize, 100);
  </script>
      <div id="header" style="height: 32px; width:100%">Coopytrek - Mission: </div>
      <div id="status" style="position: relative; width:200px; float: left">
        <div style="float:left; width:95px">Quadrant:</div><div id="sQuadrant" style="position:relative; float:left"></div><br>
        <div style="float:left; width:95px">Sector:</div><div id="sSector" style="position:relative;float:left"></div><br>
        <div style="float:left; width:100px">Objectives:</div><div id="sObjectives" style="position:relative;float:left"></div><br>
        <div style="float:left; width:95px">Energy:</div><div id="sEnergy" style="position:relative;float:left; width:100px"></div><br>
        <div style="float:left; width:95px">Damage:</div><div id="sDamage" class="percentageindicator" style="position:relative;float:left; width:100px"></div><br>
        <div style="float:left; width:95px">Shield:</div><div id="sShield" class="percentageindicator" style="position:relative;float:left; width:100px"></div><br>
      </div>
      <div id="viewportframe" class="spaceviewport" style="float: left; position: relative; width:680px; height:680px; padding: 0; background-image:url('image/starbackground.jpg');">
        <div class="BorderTop">
          <div>
           <div><center>Hyper North</center></div>
          </div>
        </div>
        <div class="BorderMiddle">
          <div>
           <div>
             <div id="viewportsizer" style="width:640px; height:640px">&nbsp;</div>
           </div>
          </div>
        </div>
        <div class="BorderBottom">
          <div>
           <div><center>Hyper South</center></div>
          </div>
        </div>
        <div id="viewport" style="float: left; position: absolute; top: 20px; left: 20px; width:640px; height:640px;"></div>

      </div>
      <div id="commandconsole" style="height: 80px; position:absolute; bottom: 2px">
       <div style="float: left">
        <div id="command" style="height:20px; background-color: #112211; border : 1px; border-style : solid; border-color : #225522;">Command: ----</div>
        <div id="com_0" class="c_button" style="background-color: #225522;"><div id="console_0"></div><div id="force_0"></div></div>
        <div id="com_1" class="c_button" style="background-color: #225522;"><div id="console_1"></div><div id="force_1"></div></div>
        <div id="com_2" class="c_button" style="background-color: #225522;"><div id="console_2"></div><div id="force_2"></div></div>
        <div id="com_3" class="c_button" style="background-color: #225522;"><div id="console_3"></div><div id="force_3"></div></div>
        <div id="com_4" class="c_button" style="background-color: #225522;"><div id="console_4"></div><div id="force_4"></div></div>
        <div id="com_5" class="c_button" style="background-color: #225522;"><div id="console_5"></div><div id="force_5"></div></div>
       </div>
       <div id="com_modifator" style="float: left; position: relative; width: 120px; height: 80px">
          <div id="mdf_ccturn" class="modifator" style="position:absolute; top: 0px; left:0px; width: 33px; height: 75px; background-position: 0px 0px;"></div>
          <div id="mdf_fincr" class="modifator" style="position:absolute; top: 0px; left:34px; width: 49px; height: 30px; background-position: -34px 0px;"></div>
          <div id="mdf_fincr" class="modifator" style="position:absolute; padding: 0px; top: 30px; left:34px; width: 49px; height: 30px; background-position: -34px -30px;">
          <form id="paramf" action="#"><input name="force" type="text" value="0" size="3"/></form></div>
          <div id="mdf_fdecr" class="modifator" style="position:absolute; top: 46px; left:34px; width: 49px; height: 30px; background-position: -34px -46px;"></div>
          <div id="mdf_cturn" class="modifator" style="position:absolute; top: 0px; left:84px; width: 34px; height: 75px; background-position: -84px 0px;"></div>
       </div>
       <div style="float: left">
        <div id="timer" style="height:20px; width:200; background-color: #552222; border : 1px; border-style : solid; border-color : #AA2222;"></div>
        <div id="com_6" class="r_button" style="background-color: #225522;"><div id="console_6"></div><div id="force_6"></div></div>
        <div id="com_7" class="r_button" style="background-color: #225522;"><div id="console_7"></div><div id="force_7"></div></div>
       </div>
      </div>
      <div id="chatterbox" style="position:absolute; top: 0px; right: 0px; margin-right: 0px; background-color: #112211; border-color: #225522; width: 16px">
        <div id="chatfoldview" style="position:absolute; top: 200px; left: 0px; height: 80px; width: 16px; background-color: #222255"></div>
        <div id="chat" style="position:absolute; top: 0px; margin-left: 16px; background-color: #111122">CHAT BOX</div>
      </div>
  </body>
</html>